﻿using Apewer;
using System;

namespace Apewer.Source
{

    /// <summary>数据库引擎的执行结果。</summary>
    public class Execute : IExecute, IToJson
    {

        private bool _success = false;
        private string _message = "";
        private int _rows = 0;

        /// <summary>语句执行成功。</summary>
        public bool Success { get => _success; }

        /// <summary>受影响的行数。</summary>
        public int Rows { get => _rows; }

        /// <summary>消息。</summary>
        public string Message { get => _message; }

        /// <summary>创建实例。</summary>
        public Execute(bool success, string message)
        {
            _success = false;
            _message = message;
        }

        /// <summary>创建实例。</summary>
        public Execute(bool success, int rows)
        {
            _success = success;
            _rows = rows;
        }

        /// <summary>创建实例，Exception 为 NULL 时候成功，非 NULL 时为失败。</summary>
        public Execute(Exception exception)
        {
            _success = exception == null;
            _message = RuntimeUtility.Message(exception);
        }

        /// <summary>从 <see cref="Execute"/> 到 <see cref="Execute"/> 的隐式转换，判断 <see cref="Execute"/> 执行成功。</summary>
        public static implicit operator bool(Execute instance)
        {
            return instance != null && instance.Success;
        }

        #region IToJson

        /// <summary>转换为 Json 对象。</summary>
        public Json ToJson()
        {
            var jsonObject = Json.NewObject();
            jsonObject.SetProperty("success", _success);
            jsonObject.SetProperty("message", _message);
            jsonObject.SetProperty("rows", _rows);
            return jsonObject;
        }

        #endregion

    }

}
